#include "progressform.h"
#include "ui_progressform.h"

//#include <QDebug>
#include <QFileDialog>

void ProgressForm::LoadProgressFromConf(std::string path)
{
    QFile file(QString::fromStdString(path));
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    ui->lb_conf->setText(path.c_str());
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        if(line.startsWith('#') || line.trimmed().isEmpty()){
            continue; // 跳过注释行或空行
        }
        // 解析每一行的数据
        QStringList fields = line.split(",");
        if (fields.size() >= 2) { // 确保至少有应用路径和是否分离的标志
            std::string appPath = fields[0].toStdString();
            bool isSeparate = (fields[1].toLower() == "yes"); // 第二个字段判断是否分离

            std::list<std::string> params;
            for (int i = 2; i < fields.size(); ++i) {
                // 只有当字段不为空时，才将其添加到参数列表中
                if (!fields[i].isEmpty()) {
                    params.push_back(fields[i].toStdString());
                }
            }

            // 如果没有参数，params将是一个空列表，这正是我们想要的
            SetAProgress(appPath, isSeparate, params); // 假设SetAProgress函数接受路径，布尔值和参数列表
        } else {
            // 处理字段不足的情况
            std::string appPath = (fields.isEmpty() || fields[0].isEmpty()) ? "" : fields[0].toStdString();
            bool isSeparate = false; // 默认值
            std::list<std::string> params;
            SetAProgress(appPath, isSeparate, params);
        }
    }
    file.close();
}

void ProgressForm::SetAProgress(std::string app,bool detach, std::list<std::string> params)
{
    // 将C++字符串转换为QString
    QString appQString = QString::fromStdString(app);
    QStringList paramsQStringList;
    for (const auto& param : params) {
        paramsQStringList << QString::fromStdString(param);
    }

    // 获取当前行数，以便添加新行
    int rowPosition = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(rowPosition);

    auto tim = new QTableWidgetItem(appQString);
    if(detach)
        tim->setToolTip("detach");
    // 设置第一列：程序文件路径
    ui->tableWidget->setItem(rowPosition, 0, tim);

    // 设置第二列：参数列表
    ui->tableWidget->setItem(rowPosition, 1, new QTableWidgetItem(paramsQStringList.join(", ")));


}

void ProgressForm::StartByLine(int i,bool NotAllowGray)
{
    // 获取程序路径
    QTableWidgetItem *appItem = ui->tableWidget->item(i, 0);
    if (!appItem) return; // 如果没有找到项目，跳过
    QString appPath = appItem->text();
    QString tlp = appItem->toolTip();

    QBrush brush = appItem->background();
    QColor color = brush.color();

    // 判断是否没有设置背景颜色
    if ( color == Qt::darkGray && NotAllowGray) {
        return;
    }

    // 获取参数列表
    QTableWidgetItem *paramsItem = ui->tableWidget->item(i, 1);
    if (!paramsItem) return; // 如果没有找到项目，跳过
    QStringList paramsList = paramsItem->text().split(", ");

    runner.AddProcess(i,appPath,tlp=="detach",paramsList);
}

void ProgressForm::SetOneRowDisable(int rowToDisable)
{
    // 遍历该行的所有列，禁用该行的所有项
    for (int column = 0; column < ui->tableWidget->columnCount(); ++column) {
        QTableWidgetItem *item = ui->tableWidget->item(rowToDisable, column);
        if (item) {
            // 移除Qt::ItemIsEnabled标志来禁用该项
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
        }
    }
}

void ProgressForm::TaskFinishedRec(int row, QString r2, QString r3)
{

    ui->tableWidget->setItem(row,2,new QTableWidgetItem(r2));
    ui->tableWidget->setItem(row,3,new QTableWidgetItem(r3));
    QTableWidgetItem *Item = ui->tableWidget->item(row, 2);
    if(r3 == "Finished"){
        Item->setBackground(Qt::green);
    }else {
        Item->setBackground(Qt::red);
    }
}

ProgressForm::ProgressForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ProgressForm)
{
    ui->setupUi(this);


    // 假设ui->tableWidget已经被正确初始化
    // 设置第一列宽度为200像素
    ui->tableWidget->setColumnWidth(0, 300);

    // 设置第二列宽度为300像素
    ui->tableWidget->setColumnWidth(1, 300);

    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->tableWidget, &QTableWidget::customContextMenuRequested, this, &ProgressForm::onTableWidgetContextMenu);

    connect(&runner,&ThreadRunner::TaskFinished,this,&ProgressForm::TaskFinishedRec);
}


void ProgressForm::onTableWidgetContextMenu(const QPoint &pos)
{
    QTableWidgetItem *item = ui->tableWidget->itemAt(pos);
    QString ts;
    QBrush cols;
    if (!item) {
        return;
    }
    QBrush brush = item->background();
    QColor color = brush.color();

    if (!color.isValid() || color == Qt::NoBrush) {
        ts = tr("设置无效");
        cols = Qt::darkGray;
    }
    else if (color == Qt::darkGray) {
        ts = tr("取消无效");
        cols = Qt::NoBrush;
    }
    else {
        cols = Qt::NoBrush;
    }
    QMenu menu;
    QAction *selectAll = menu.addAction(tr("Select ALL"));
    selectAll->setEnabled(false);
    menu.addSeparator();
    QAction *clear = menu.addAction(tr("Clean Content"));
    menu.addSeparator();
    QAction *unvalid = menu.addAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning),ts);
    clear->setEnabled(false);

    QAction *selFile = menu.addAction(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon),tr("选择文件"));
    menu.addSeparator();


    connect(selectAll, &QAction::triggered, [=](){
        ui->tableWidget->selectAll();
    });

    connect(clear, &QAction::triggered, [=](){
        ui->tableWidget->clear();
    });

    connect(selFile, &QAction::triggered, [=](){
        QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("All Files (*);;Text Files (*.txt)"));
        item->setText(fileName);
    });

    connect(unvalid, &QAction::triggered, [=](){
        item->setBackground(cols);
    });

    menu.exec(QCursor::pos());
}

ProgressForm::~ProgressForm()
{
    delete ui;
}


void ProgressForm::on_pb_startByTable_clicked()
{
    runner.clear();
    // 遍历表格中的每一行
    for (int i = 0; i < ui->tableWidget->rowCount(); ++i) {
        StartByLine(i);
    }
    runner.start();

}


void ProgressForm::on_pb_openConf_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("All Files (*);;Text Files (*.txt)"));
    if(!fileName.isEmpty()){
        if(!ui->cb->isChecked()){
            ui->tableWidget->setRowCount(0);
        }

        LoadProgressFromConf(fileName.toStdString());
    }

}

void ProgressForm::on_pb_startCurrent_clicked()
{
    runner.clear();
    int currentRow = ui->tableWidget->currentRow();
    StartByLine(currentRow,false);
    runner.start();
}
